package com.kalman.webx;

import static com.google.common.base.Strings.isNullOrEmpty;

import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class IpAddress {

	private final static Logger log = LoggerFactory.getLogger(IpAddress.class);
	/**
	 * 获取客户端请求的ip地址，若需要打印客户端的ip地址，请使用<code> getIpAddress(HttpServletRequest request,boolean logIp)</code>
	 * @param request
	 * @return
	 */
	public static String getIpAddress(HttpServletRequest request){
		return getIpAddress(request, false);
	}
	/**
	 * 获取客户端请求的ip地址
	 * @param request
	 * @param logIp 是否需要在日志文件里面打印ip日志
	 * @return
	 */
	public static String getIpAddress(HttpServletRequest request,boolean logIp){
		String ip = request.getHeader("x-forwarded-for");
		if (isNullOrEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (isNullOrEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (isNullOrEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		if (logIp) {
			log.warn("ip:" + ip);
			log.warn("x-forwarded-for:" + request.getHeader("x-forwarded-for"));
			log.warn("Proxy-Client-IP:" + request.getHeader("Proxy-Client-IP"));
			log.warn("WL-Proxy-Client-IP:"
					+ request.getHeader("WL-Proxy-Client-IP"));
			Enumeration<?> en = request.getHeaderNames();
			String headerName = "";
			String headerValue = "";
			StringBuilder requestHeader = new StringBuilder("");
			while (en.hasMoreElements()) {
				headerName = (String) en.nextElement();
				headerValue = request.getHeader(headerName);
				requestHeader.append(headerName);
				requestHeader.append(":");
				requestHeader.append(headerValue);
				requestHeader.append("==");
				if ("cookie".equals(headerName)) {
					log.warn("cookielength:" + headerValue.length());
				}
			}
			log.warn(requestHeader.toString());
			log.warn("requestHeaderlength:" + requestHeader.length());
		}
		String sep = ",";// 代理时会有是逗号分隔的ip
		if (ip != null && ip.indexOf(sep) != -1) {
			try {
				ip = ip.split(sep)[0].trim();
			} catch (Exception e) {
				log.warn("get ip error.", e);
			}
		}
		return ip;
	}
}